// const taos = require('td-connector')
import taos from '@tdengine/websocket'
// import taos from 'td-connector'

const { WebSocket } = require('ws')

// 数据库连接配置
const connectionConfig = {
  host: 'ws://47.97.194.8:9041',
  user: 'root',
  password: 'yanboot',
  // database: 'yanboot_edge'
  database: 'yanboot_iot_dev'
}

let conn

// 连接TDengine
export async function connectToTDengine(args) {
  try {
    console.log('connecting to TDengine...', args)
    const { ip, port, username, password, database } = JSON.parse(args)
    connectionConfig.password = password
    connectionConfig.host = `ws://${ip}:${port}`
    connectionConfig.user = username
    connectionConfig.database = database
    let conf = new taos.WSConfig(connectionConfig.host)
    conf.setUser(connectionConfig.user)
    conf.setPwd(connectionConfig.password)
    conf.setDb(connectionConfig.database)
    conn = await taos.sqlConnect(conf)
    return true
  } catch (err) {
    console.error('Error connecting to TDengine:', err)
    return false
  }
}

//切换连接信息
async function changeConnection(connection) {
  const { ip, port, username, password, database } = JSON.parse(connection)
  connectionConfig.password = password
  connectionConfig.host = `ws://${ip}:${port}`
  connectionConfig.user = username
  connectionConfig.database = database
  return true
}

// 执行查询
export async function executeQuery(sql) {
  if (!conn) {
    throw new Error('Database connection not established')
  }

  try {
    const rows = []
    const result = await conn.query(sql)
    while (await result.next()) {
      let row = result.getData()
      console.log('ts: ' + row[0] + ', current: ' + row[1] + ', location:  ' + row[2])
      rows.push(row)
    }
    return rows
  } catch (err) {
    console.error('Error executing query:', err)
    throw new Error(`Query failed: ${err.message}`)
  }
}

//切换数据库
async function getConnInfo() {
  console.log(conn, 'conn')
  if (conn) {
    return JSON.stringify(connectionConfig)
  } else {
    return null
  }
}

export function register(ipcMain) {
  ipcMain.handle('changeConnection', function (event, connection) {
    return changeConnection(connection)
  })

  ipcMain.handle('getConnInfo', function () {
    return getConnInfo()
  })

  ipcMain.handle('doQuery', function (event, sql) {
    return executeQuery(sql)
  })

  ipcMain.handle('connectToTDengine', function (event, args) {
    return connectToTDengine(args)
  })

  // ipcMain.handle('getCurrConnection', function (event) {
  //   return getCurrConnection()
  // })
  //
  // ipcMain.handle('getCurrDatabase', function (event) {
  //   return getCurrDatabase()
  // })
}

module.exports = {
  register
}
